﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RecipeBookBusiness
{
    public class Category
    {
        private RecipeBookEntities _entities = new RecipeBookEntities();
        private int _id;
        private string _name;

        public Category(int catID)
        {
            loadCategoryClass(catID);
        }

        public Category(string name)
        {
            try
            {
                CategoryDataRow cdr = new CategoryDataRow();
                cdr.Name = name;

                //Save to DB and get ID
                _entities.AddToCategoryDataRowSet(cdr);
                _entities.SaveChanges();
                int newCategoryID = 0;
                foreach (CategoryDataRow idCdr in _entities.CategoryDataRowSet)
                {
                    if (idCdr.ID > newCategoryID)
                        newCategoryID = idCdr.ID;
                }
                loadCategoryClass(newCategoryID);
            }
            catch (Exception ex)
            {
                //TODO: Real exception handling
                Console.Write(ex.Message);
            }
        }

        public void UpdateCategory(string name)
        {
            CategoryDataRow categoryDR = (from c in _entities.CategoryDataRowSet
                                          where c.ID == _id
                                          select c).FirstOrDefault();
            bool needToUpdate = false;
            if (!_name.Equals(name))
            {
                _name = name;
                needToUpdate = true;
            }

            if (needToUpdate)
            {
                categoryDR.Name = _name;
                _entities.SaveChanges();
            }
        }

        public void DeleteCategory()
        {
            CategoryDataRow cdr = (from c in _entities.CategoryDataRowSet
                                 where c.ID == _id
                                 select c).FirstOrDefault();
            _entities.DeleteObject(cdr);
            _entities.SaveChanges();
        }

        private void loadCategoryClass(int catID)
        {
            CategoryDataRow categoryDR = (from c in _entities.CategoryDataRowSet
                                          where c.ID == catID
                                          select c).FirstOrDefault();
            _id = categoryDR.ID;
            _name = categoryDR.Name;
        }

        public int ID
        {
            get
            {
                return _id;
            }
        }

        public string Name
        {
            get
            {
                return _name;
            }
        }
    }
}
